from 数据库操作.CreateMysqlCon import CreateMysqlCon

class GetBlogList:

    def __init__(self):
        self.con = CreateMysqlCon().get_con()
        if not self.con:
            raise ConnectionError("数据库连接失败，请检查配置或网络")
        self.cursor = self.con.cursor()

    def get_my_blog_list(self, username):
        sql = ("select b.ID, b.title, b.details, b.publish_date from blog_list as b,"
               "user_data as u where u.username = %s and b.user_id = u.ID")
        self.cursor.execute(sql, username)
        result = self.cursor.fetchall()
        return result
        
    def get_blog_list(self):
        sql = ("select b.ID, b.title, u.username, b.details, b.publish_date from blog_list as b,"
               "user_data as u where b.user_id = u.ID ORDER BY b.publish_date DESC")
        self.cursor.execute(sql)
        result = self.cursor.fetchall()
        return result
        
    def delete_blog(self, blog_id, username):
        """删除博客（只能删除自己的博客）"""
        try:
            # 先检查是否是自己的博客
            sql = """SELECT b.ID FROM blog_list b 
                   JOIN user_data u ON b.user_id = u.ID 
                   WHERE b.ID = %s AND u.username = %s"""
            self.cursor.execute(sql, (blog_id, username))
            if not self.cursor.fetchone():
                return False  # 不是自己的博客或博客不存在
            
            # 删除博客
            sql = "DELETE FROM blog_list WHERE ID = %s"
            self.cursor.execute(sql, (blog_id,))
            self.con.commit()
            return True
        except Exception as e:
            print(f"删除博客失败: {e}")
            return False
            
    def get_blog_by_id(self, blog_id):
        """根据ID获取博客详情"""
        try:
            sql = """SELECT b.ID, b.title, u.username, u.ID as user_id, b.details, b.publish_date 
                   FROM blog_list b 
                   JOIN user_data u ON b.user_id = u.ID 
                   WHERE b.ID = %s"""
            self.cursor.execute(sql, (blog_id,))
            return self.cursor.fetchone()
        except Exception as e:
            print(f"获取博客详情失败: {e}")
            return None